package org.advanced;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author John.zhang
 * @version Id: RpcProxyServer, v 1.0 2020/12/14 17:19 ZhiYong Exp $
 */
public class RpcProxyServer implements Runnable {

    final ExecutorService executorService = Executors.newFixedThreadPool(5);

    private Selector selector;

    private ServerSocketChannel serverSocketChannel;

    private volatile boolean stop;

    private Object service;

    public RpcProxyServer() {
    }

    /**
     * 基于NIO实现优化RPC
     *
     * @param service
     * @param port
     */
    public RpcProxyServer(Object service, int port) {
        this.service = service;
        try {
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.socket().bind(new InetSocketAddress(port));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (!stop) {
            try {
                //阻塞
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey next = iterator.next();
                    iterator.remove();
                    try {
                        handleRequest(next);
                    } catch (Exception e) {
                        //处理失败就取消通道并关闭通道
                        next.cancel();
                        next.channel().close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    private void handleRequest(SelectionKey selectionKey) throws IOException {
        if (selectionKey.isValid()) {
            if (selectionKey.isAcceptable()) {
                ServerSocketChannel channel = (ServerSocketChannel) selectionKey.channel();
                //取出具体的连接，不会阻塞
                SocketChannel socketChannel = channel.accept();
                socketChannel.configureBlocking(false);
                socketChannel.register(selector, SelectionKey.OP_READ);
            } else if (selectionKey.isReadable()) {
                SocketChannel channel = (SocketChannel) selectionKey.channel();
                new NioProcessorHandler(channel, service).doProcessor();
            }
        }
    }


    /**
     * BIO模式的RPC
     *
     * @param service
     * @param port
     */
    public void publish(Object service, int port) {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(port);
            while (true) {
                //这里会进行阻塞
                final Socket accept = serverSocket.accept();
                //上面收到请求后会丢到线程池执行
                executorService.execute(new ProcessorHandler(accept, service));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
